# -*- coding=utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import tornado.web
import tornado.httpserver
import tornado.ioloop
import os.path,os,ldap_login
import pwdconfig as P
import sqlite3
def dbconn(sql):
    conn = sqlite3.connect("IACS.s3db")
    conn.text_factory = str
    cur = conn.cursor()
    cur.execute(sql)
    conn.commit()
    return cur.fetchall()
    cur.close()
    conn.close()
settings = {
    "static_path" : os.path.join(os.path.dirname(__file__), "static"),
    "template_path" : os.path.join(os.path.dirname(__file__), "templates"),
    "login_url": "/login",
    }
class LoginHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        return self.get_cookie("login")
class main(tornado.web.RequestHandler):
    def get(self):
        status = "0"
        user = "None"
        location='None'
        if self.get_cookie('login'):            #通過Cookie判斷用戶是否已經登入
            status = "1"
            user = self.get_cookie('login')
            location = self.get_cookie('location')
        self.render('main.html',status=status,user=user,location=location)
    
class login(tornado.web.RequestHandler):
    def post(self):
        username = self.get_argument('username','')
        password = self.get_argument('password','')#獲取用戶輸入
        LoginStatus = False
        USER = dbconn("select USER,LOCATION from USERS where USER='%s'" % username.lower())
        if USER:
            try:
                if ldap_login.login(r"cminl\%s" % username.lower(),password):       #LDAP認證判斷用戶輸入的用戶名&密碼是否正確
                    LoginStatus = True
                else:
                    LoginStatus = False
                if LoginStatus:
                    location = USER[0][1]
                    self.set_cookie("login",username.lower())
                    self.set_cookie("location",location)
                    self.redirect("#")
                else:
                    self.write("0")
            except Exception as e:
                self.write("0")
        else:
            self.write("404")

    def get(self):
        self.redirect("/")
class pwdchange(LoginHandler):
    @tornado.web.authenticated
    def post(self):
        try:
            password = self.get_argument('password','')
            location = self.get_argument('location','')
        except:
            self.write("000")
        else:
            if P.change(location,'PWD',password):
                self.write("666")
            else:
                self.write("000")
class perto(LoginHandler):
    @tornado.web.authenticated
    def post(self):
        try:
            loginuser = self.get_argument('loginuser','').lower()
            user = self.get_argument('user','').strip(r"CMINL\\").lower()
            location = self.get_argument('location','')
        except:
            self.write("000")
        else:
            try:
                dbconn("UPDATE USERS SET USER='%s' WHERE LOCATION='%s' AND USER='%s'" % (user,location,loginuser))
            except:
                self.write("000")
            else:
                self.write("666")
                


class logout(tornado.web.RequestHandler):
    def get(self):
        self.clear_all_cookies()
        self.redirect("/")
App = tornado.web.Application([
    (r'/',main),                    #主頁
    (r'/login',login),              #系統登入
    (r'/pwdchange',pwdchange),      #密碼修改
    (r'/perto',perto),
    (r'/logout',logout),            #系統登出
    ],**settings)
if __name__ == "__main__":
    http_server=tornado.httpserver.HTTPServer(App)
    http_server.listen(8000)
    tornado.ioloop.IOLoop.instance().start()
